<template>
    <div class="template-manager">
      <h3>我的模板</h3>
      <button class="refresh-btn" @click="fetchTemplates">刷新</button>
      <div v-if="isLoading" class="loading">正在加载...</div>
      <ul v-else-if="templates.length > 0" class="template-list">
        <li v-for="template in templates" :key="template._id" class="template-item">
          <span class="template-name" @click="handleSelectTemplate(template)">
              {{ template.name }}
              <small>{{ new Date(template.createdAt).toLocaleDateString() }}</small>
          </span>
          <div class="actions">
            <button @click="loadTemplate(template._id)" title="加载到画布">📥</button>
            <button @click="deleteTemplate(template._id)" title="删除模板">🗑️</button>
          </div>
        </li>
      </ul>
      <div v-else class="no-templates">没有已保存的模板</div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, defineEmits } from 'vue';
  import axios from 'axios';
  import { useTemplateStore } from '@/stores/templateStore';
  
  const store = useTemplateStore();
  const templates = ref<any[]>([]);
  const isLoading = ref(false);
  
  const emit = defineEmits(['templateSelected']);
  
  const fetchTemplates = async () => {
    isLoading.value = true;
    try {
      const response = await axios.get('http://localhost:4000/api/templates');
      templates.value = response.data;
    } catch (error) {
      console.error('获取模板列表失败:', error);
      alert('获取模板列表失败');
    } finally {
      isLoading.value = false;
    }
  };
  
  const loadTemplate = async (id: string) => {
    if (store.elements.length > 0 && !confirm('加载模板将会覆盖当前画布，确定吗？')) {
        return;
    }
    try {
      const response = await axios.get(`http://localhost:4000/api/templates/${id}`);
      
      // 【核心修正】将整个 response.data 对象传递给 store action
      store.loadTemplate(response.data);
  
    } catch (error) {
      console.error('加载模板失败:', error);
      alert('加载模板失败');
    }
  };
  
  const deleteTemplate = async (id: string) => {
    if (!confirm('确定要永久删除这个模板吗？')) return;
    try {
      await axios.delete(`http://localhost:4000/api/templates/${id}`);
      alert('删除成功');
      fetchTemplates(); // 删除后刷新列表
    } catch (error) {
      console.error('删除模板失败:', error);
      alert('删除模板失败');
    }
  };
  
  const handleSelectTemplate = (template: any) => {
      emit('templateSelected', template);
  };
  
  onMounted(fetchTemplates);
  </script>
  
  <style scoped>
  /* 样式无变化 */
  .template-manager { border-top: 1px solid #ddd; margin-top: 1rem; padding-top: 1rem; }
  .refresh-btn { width: auto; float: right; padding: 2px 5px; }
  .template-list { list-style: none; padding: 0; margin-top: 1rem; }
  .template-item { display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; border-bottom: 1px solid #eee; }
  .template-item:hover { background-color: #e9ecef; }
  .template-name { cursor: pointer; display: flex; flex-direction: column; }
  .template-name small { font-size: 0.7rem; color: #888; }
  .actions button { background: none; border: none; cursor: pointer; font-size: 1rem; }
  .no-templates, .loading { text-align: center; color: #888; margin-top: 1rem; }
  </style>